package xyz.poke.business.tool.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import xyz.poke.business.tool.common.ErrorCode;
import xyz.poke.business.tool.constants.DbConstants;
import xyz.poke.business.tool.convert.UserConvert;
import xyz.poke.business.tool.dto.UserDTO;
import xyz.poke.business.tool.entity.User;
import xyz.poke.business.tool.exception.BusinessException;
import xyz.poke.business.tool.mapper.UserMapper;
import xyz.poke.business.tool.param.UserParam;
import xyz.poke.business.tool.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.poke.business.tool.utils.CheckerUtils;
import xyz.poke.business.tool.utils.MySecretUtils;
import xyz.poke.business.tool.utils.TokenUtils;

import java.util.Objects;

/**
 * <p>
 * 商品基本信息表 服务实现类
 * </p>
 *
 * @author 迫壳
 * @since 2024-02-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public UserDTO login(UserParam param) {
        User user = getOne(new QueryWrapper<User>().eq(DbConstants.USERNAME, param.getUsername()));
        CheckerUtils.notNull(user, "无此账号，请注册");
        CheckerUtils.isTrue(user.getPassword().equals(SecureUtil.md5(param.getPassword())), "密码错误");
        UserDTO userDTO = UserConvert.INSTANCE.toDTO(user);
        String token = TokenUtils.createToken(userDTO);
        userDTO.setToken(token);
        return userDTO;
    }

    @Override
    public Boolean register(UserParam param) {
        User user = getOne(new QueryWrapper<User>().eq(DbConstants.USERNAME, param.getUsername()));
        CheckerUtils.isNull(user, "账号已经注册过了");
        String newPassword = SecureUtil.md5(param.getPassword());
        user = new User();
        user.setUsername(param.getUsername());
        user.setPassword(newPassword);
        if (!CollectionUtils.isEmpty(param.getRoleIds())) {
            String roleStrIds = String.join("-", param.getRoleIds());
            user.setRoleIds(roleStrIds);
        }
        return this.save(user);
    }
}
